<template>
  <div class="card">
    <dv-border-box-13 title="重点选题" :color="['#168BF9', '#112F7C']">
      <!-- 添加标题组件 -->
      <CardTitle
        title="重点选题"
        :show-detail="false"
        @detail-click="handleDetail"
      />
      <div class="content-wrapper">
        <!-- 图表区域 - 垂直排列 -->
        <div class="charts-container">
          <!-- 近半年选题发布趋势柱状图 -->
          <div class="chart-item vertical-item">
            <div class="chart-title">近半年选题发布趋势</div>
            <div class="chart-container">
              <div ref="trendChart" class="chart"></div>
            </div>
          </div>

          <!-- 最新选题滚动表格 -->
          <div class="table-container">
            <div class="table-title">最新发布选题</div>
            <div class="table">
              <dv-scroll-board
                :config="scrollBoardConfig"
                style="width: 100%; height: 170px"
                class="custom-scroll-board"
              />
            </div>
          </div>
        </div>
      </div>
    </dv-border-box-13>
  </div>
</template>

<script>
import * as echarts from "echarts";
import CardTitle from "../components/card-title.vue"; // 引入标题组件
import { currentPOST } from "api/modules";
export default {
  name: "ClueAnalysis",
  components: {
    CardTitle,
  },
  data() {
    return {
      reportTab: "district", // 报送量图表tab
      // 近半年选题发布数据
      trendData: [],
      // 最新选题数据
      latestTopics: [],
    };
  },
  computed: {
    // 滚动表格配置
    scrollBoardConfig() {
      return {
        data: this.latestTopics.map((item) => [
          item.name || item.title || "暂无标题",
          item.createdTime || item.publishTime || "--",
        ]),
        headerBGC: "rgba(5, 64, 128, 0.8)",
        oddRowBGC: "rgba(10, 44, 94, 0.3)",
        evenRowBGC: "rgba(5, 64, 128, 0.2)",
        headerHeight: 40,
        rowNum: 4,
        columnWidth: [600, 300],
        align: ["left", "center"],
        waitTime: 3000,
        carousel: "single",
        hoverPause: true,
        textStyle: {
          color: "#bae7ff",
          fontSize: 14,
        },
        headerTextStyle: {
          color: "#ffffff",
          fontSize: 14,
          fontWeight: "bold",
        },
      };
    },
  },
  methods: {
    // 初始化图表
    initCharts() {
      this.getTopicLineData();
      this.getReportList();
    },

    getTopicLineData() {
      currentPOST("rightTopTopicLineClues")
        .then((res) => {
          if (res.code === 0) {
            // 处理API返回的数据格式
            this.trendData = (res.data || []).map((item) => ({
              date: this.formatDate(item.date), // 格式化日期显示
              count: parseInt(item.count) || 0, // 确保count是数字类型
            }));
            this.initTrendChart();
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("趋势图请求失败:", error);
        });
    },

    getReportList() {
      currentPOST("rightTopTopicListClues", {
        lastDay: 100,
        pageSize: 100,
        current: 1,
      })
        .then((res) => {
          if (res.code === 0) {
            // 处理API返回的数据格式
            if (res.data && res.data.data) {
              this.latestTopics = res.data.data.map((item) => ({
                id: item.id,
                name: item.name,
                content: item.content,
                createdTime: this.formatDateTime(item.createdTime),
                createdAccountName: item.createdAccountName,
                createdOrganizationName: item.createdOrganizationName,
              }));
            } else {
              this.latestTopics = [];
            }
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("选题列表请求失败:", error);
        });
    },

    // 格式化日期显示（从 "2025-10" 到 "10月"）
    formatDate(dateStr) {
      if (!dateStr) return "";
      const parts = dateStr.split("-");
      if (parts.length >= 2) {
        const month = parseInt(parts[1]);
        return `${month}月`;
      }
      return dateStr;
    },

    // 格式化日期时间显示
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return "--";
      // 从 "2025-10-15 16:56:35" 到 "2024-10-15 16:56"
      return dateTimeStr.substring(0, 16);
    },

    // 初始化近半年选题发布趋势柱状图
    initTrendChart() {
      if (!this.$refs.trendChart) return;

      this.trendChart = echarts.init(this.$refs.trendChart);
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
            return `${params[0].name}<br/>发布数量: ${params[0].value}`;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%",
          top: "15%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.trendData.map((item) => item.date),
          axisLabel: {
            color: "#bae7ff",
            fontSize: 12,
          },
          axisLine: {
            lineStyle: {
              color: "#2d5278",
            },
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#bae7ff",
            fontSize: 12,
          },
          axisLine: {
            lineStyle: {
              color: "#2d5278",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(45, 82, 120, 0.3)",
              type: "dashed",
            },
          },
        },
        series: [
          {
            name: "发布数量",
            type: "bar",
            barWidth: "40%",
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#36a3ff" },
                { offset: 0.3, color: "#1890ff" },
                { offset: 0.7, color: "#096dd9" },
                { offset: 1, color: "#0050b3" },
              ]),
              borderRadius: [4, 4, 0, 0],
              shadowBlur: 8,
              shadowColor: "rgba(24, 144, 255, 0.5)",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 15,
                shadowColor: "rgba(24, 144, 255, 0.8)",
              },
            },
            data: this.trendData.map((item) => item.count),
            label: {
              show: true,
              position: "top",
              color: "#ffffff",
              fontSize: 12,
              fontWeight: "bold",
              formatter: "{c}",
            },
          },
        ],
      };
      this.trendChart.setOption(option);
    },

    // 报送量tab切换
    handleReportTabChange() {
      if (this.reportChart) {
        this.initReportChart();
      }
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.trendChart) {
        this.trendChart.resize();
      }
      if (this.reportChart) {
        this.reportChart.resize();
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
    });

    // 监听窗口大小变化
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.trendChart) {
      this.trendChart.dispose();
    }
    if (this.reportChart) {
      this.reportChart.dispose();
    }
    // 移除事件监听
    window.removeEventListener("resize", this.handleResize);
  },
};
</script>

<style lang="scss" scoped>
.card {
  margin-top: 30px;
  height: 500px;
  display: flex;
  justify-content: center;
}

.content-wrapper {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  margin-top: -30px;
}

// 图表容器 - 垂直排列
.charts-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: 400px;
}

.chart-item {
  background: rgba(5, 64, 128, 0.2);
  border-radius: 8px;
  padding: 12px;
  box-sizing: border-box;
  position: relative;

  // 垂直排列的项
  &.vertical-item {
    flex: 1;
    min-height: 180px;
    display: flex;
    flex-direction: column;
  }

  .chart-title {
    color: #bae7ff;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 10px;
    flex-shrink: 0;
  }

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    flex-shrink: 0;

    .tab-switch {
      ::v-deep .el-radio-group {
        .el-radio-button {
          .el-radio-button__inner {
            background: rgba(5, 64, 128, 0.5);
            color: #bae7ff;
            border: 1px solid #2d5278;
            font-size: 12px;
            padding: 5px 10px;

            &:hover {
              color: #ffffff;
              background: rgba(45, 82, 120, 0.8);
            }
          }

          &.is-active {
            .el-radio-button__inner {
              background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
              color: #ffffff;
              border-color: #1890ff;
            }
          }
        }
      }
    }
  }

  .chart-container {
    position: relative;
    width: 100%;
    flex: 1;
    min-height: 150px;

    .chart {
      width: 100%;
      height: 100%;
    }
  }
}

.table-container {
  border-radius: 8px;
  padding: 12px;
  .table-title {
    color: #bae7ff;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 10px;
  }
  .table {
    width: 100%;
    flex: 1;
  }
}
// 滚动表格样式调整
.custom-scroll-board {
  ::v-deep .dv-scroll-board {
    .header {
      background: rgba(5, 64, 128, 0.8) !important;
    }

    .rows {
      .row-item {
        background: transparent !important;

        &:nth-child(odd) {
          background: rgba(10, 44, 94, 0.3) !important;
        }

        &:nth-child(even) {
          background: rgba(5, 64, 128, 0.2) !important;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .card {
    height: 700px;
  }

  .charts-container {
    gap: 12px;
  }

  .chart-item.vertical-item {
    min-height: 200px;
  }
}
</style>
